package com.ranqianhui.ojbackendjudgeservice.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import com.ranqianhui.ojbackendcommon.common.ErrorCode;
import com.ranqianhui.ojbackendcommon.exception.BusinessException;
import com.ranqianhui.ojbackendjudgeservice.codesandbox.CodeSandbox;
import com.ranqianhui.ojbackendmodel.model.codesandbox.ExecuteCodeRequest;
import com.ranqianhui.ojbackendmodel.model.codesandbox.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;

/**
 * 远程代码沙箱(实际调用接口的代码沙箱)
 */
public class RemoteCodeSanbox implements CodeSandbox {
    private static final String AUTH_REQUEST_HEADER="auth";
    private static final String AUTH_REQUEST_SECRET="ranqianhui";
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String url="http://localhost:8888/executeCode";
        String json= JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        if (!StringUtils.isNotBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_EROOR,"executeCode remoteSandbox error"+responseStr);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
